/* ***************************
* 数据门户操作界面JS
* @Editer wangjunfu
* ****************************/

$(function () {
    //名称修改后修改对应隐藏名称
    $("#query_name_input").change(function () {
        var newname = $(this).val();
        if (newname === "") {
            return showInfoAlert("数据门户名称不能为空！");
        }
        $("#dashboardname").val(newname);
    });

    $("#unfold-widget").click(function () {
        //可视化编辑
        var b = $("#optionmaindiv").hasClass("no-widget");
        if (b) {
            $("#optionmaindiv").removeClass("no-widget");
        } else {
            $("#optionmaindiv").addClass("no-widget");
        }
    });

    //关闭可视化编辑
    $("#close-main-widget").click(function () {
        $("#optionmaindiv").addClass("no-widget");
    });
});

function showDataAddModal() {
    //默认先查询仪表盘数据
    $("#add_data_type").val(1);

    execQueryDatas();
    $("#addDataModal").modal("show");
}

$(function () {
    //绑定添加数据查询按钮事件
    $("#searchList").click(function () {
        $("#currentpage").val(1);
        execQueryDatas();
    });
});

/**
 * 获取数据门户数据
 */
function execQueryDatas() {
    ajax({
        url: "/analysis/dashboard/getAddDatas",
        data: $("#queryform").serialize(),
        success: function (page) {
            var databody = $("#data_body");
            databody.empty();
            //分页信息
            var end = page.start + page.pageSize;
            if (end > page.totalItems) {
                end = page.totalItems;
            }
            $("#pagination-info").text("显示 " + page.start + " - " + end + " 共 " + page.totalItems + " 条记录");
            lastPage = page.totalPages;
            if (page.pn == 1) { //当前页码为1时  第一页和上一页不可用
                $("#queryFBtn").addClass("disabled");
                $("#queryPBtn").addClass("disabled");
            } else {
                $("#queryFBtn").removeClass("disabled");
                $("#queryPBtn").removeClass("disabled");
            }

            if (page.pn == lastPage) { //当前页码为最后一页时  最后一页和下一页不可用
                $("#queryNBtn").addClass("disabled");
                $("#queryLBtn").addClass("disabled");
            } else {
                $("#queryNBtn").removeClass("disabled");
                $("#queryLBtn").removeClass("disabled");
            }

            var rows = page.items;
            //数据信息
            if (rows.length > 0) {
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    var tr = $("<tr>");
                    var td_id = $("<td>" + row.id + "</td>");
                    var td_name = $("<td>" + row.name + "</td>");
                    var td_owner = $("<td>" + row.owner + "</td>");
                    var ctime = moment(row.ctime).fromNow();
                    var td_ctime = $("<td>" + ctime + "</td>");
                    var td_options = $("<td></td>");
                    var option_show = $('<a style="margin-right: 5px" href="javascript:void(0)" onclick="previewAddData(' + row.type + ',' + row.id + ')"><span class="label label-table label-primary" style="font-size: 12px;">预览</span></a>');
                    var option_add = $('<a style="margin-right: 5px" href="javascript:void(0)" onclick="addToDashboard(' + row.type + ',' + row.id + ',\'' + row.name + '\',\'\')"><span class="label label-table label-success" style="font-size: 12px;">添加</span></a>&nbsp;&nbsp;');

                    td_options.append(option_show);
                    td_options.append(option_add);

                    tr.append(td_id);
                    tr.append(td_name);
                    tr.append(td_owner);
                    tr.append(td_ctime);
                    tr.append(td_options);
                    databody.append(tr);
                }
            } else {
                return showInfoAlert("没有查询到记录！");
            }
        }
    });
}

/**
 * 获取数据门户数据 分页
 */
var lastPage = 1;
function pageQuery(type) {
    var cpage = Number($("#currentpage").val());
    var tpage = 1;  //目标页
    switch (type) {
        case "f":   //第一页
            tpage = 1;
            break;
        case "p":   //上一页
            tpage = cpage - 1;
            if (tpage <= 0) {
                return showInfoAlert("没有上一页了！");
            }
            break;
        case "n":   //下一页
            tpage = cpage + 1;
            if (tpage > lastPage) {
                return showInfoAlert("没有下一页了！");
            }
            break;
        case "l":   //最后一页
            tpage = lastPage;
            break;
        case "j":   //跳转
            tpage = Number($("#jumpinput").val());
            if (tpage > lastPage || tpage <= 0 || tpage === "") {
                return showInfoAlert("错误的页数范围！页码范围[1~" + lastPage + "]");
            }
            break;
    }
    $("#currentpage").val(tpage);

    execQueryDatas();
}

/**
 * 预览选择的门户数据
 * @param type
 * @param id
 */
function previewAddData(type, id) {
    switch (type) {
        case 1:
            window.open("/analysis/charts/preview?chartid=" + id);
            break;
        case 2:
            window.open("/analysis/spreadsheet/preview?sheetid=" + id);
            break;
        case 3:
            window.open("/analysis/composesheet/preview?composeid=" + id);
            break;
        case 4:
            window.open("/analysis/composechart/preview?chartid=" + id);
            break;
    }
}

/**
 * 添加到门户
 * @param type
 * @param id
 * @param name
 */
function addToDashboard(type, id, name, infoid, special) {
    var hasAdd = false;

    //判断是否已经添加过
    $("#datainfos").find("li[name=datainfo]").each(function (i, di) {
        var temptype = $(di).find("input[name=datatype]").val();
        var tempid = $(di).find("input[name=dataid]").val();
        if (type == temptype && id == tempid) {
            hasAdd = true;
            return false;
        }
    });

    if (hasAdd) {
        return showInfoAlert("【" + name + "】已经添加到数据门户中了！");
    }

    var li = $('<li  class="column-item column-measure" name="datainfo">');
    var li_span_icon = $('<span title="电子表格数据" style="font-size: 12px" class="iconfont icon-table pull-left"></span>');
    switch (type) {
        case 1:
            li_span_icon = $('<span title="数据图表数据" style="font-size: 12px" class="iconfont icon-chart pull-left"></span>');
            break;
        case 2:
            li_span_icon = $('<span title="电子表格数据" style="font-size: 12px" class="iconfont icon-table pull-left"></span>');
            break;
        case 3:
            li_span_icon = $('<span title="高级表格数据" style="font-size: 12px" class="iconfont icon-group pull-left"></span>');
            break;
        case 4:
            li_span_icon = $('<span title="高级图表数据" style="font-size: 12px" class="iconfont icon-group pull-left"></span>');
            break;
    }

    var li_span_name = $(' <span class="data-item" style="width: 150px;margin-left: 2px" title="' + name + '" >' + name + '</span>');
    var li_remove = $('<span title="移除门户数据" class="iconfont icon-remove pull-right" onclick="removeData(this,' + type + ',' + id + ',\'' + name + '\')"></span>');

    var li_edit_box_type = $('<span title="设置图形样式" style="font-size: 12px;" class="iconfont icon-setup pull-right" ></span>');
    li_edit_box_type.click(function () {
        _box_type_edit_li = $(this).closest("li[name=datainfo]");
        var type = _box_type_edit_li.find("input[name=specialcss]").val();
        $("#boxcss").val(type);
        $("#editBoxType").modal("show");
    });

    var li_hidden_infoid = $("<input type='hidden' id='infoid_" + type + "_" + id + "' name='infoid' value='" + 0 + "'>");
    if (infoid) {
        li_remove = $('<span title="移除门户数据" class="iconfont icon-remove pull-right" onclick="removeData(this,' + type + ',' + id + ',\'' + name + '\',' + infoid + ')"></span>');
        li_hidden_infoid = $("<input type='hidden' id='infoid_" + type + "_" + id + "' name='infoid' value='" + infoid + "'>");
    }

    var li_hidden_id = $("<input type='hidden' name='dataid' value='" + id + "'>");
    var li_hidden_type = $("<input type='hidden' name='datatype' value='" + type + "'>");
    var li_hidden_name = $("<input type='hidden' name='dataname' value='" + name + "'>");

    var style = "";
    if (special != "" && special != null) {
        var style = "";
        console.log(special);
        if (special.hasOwnProperty('div_style')) {
            style = special.div_style;
        }
    }
    var li_hidden_css = $("<input type='hidden' name='specialcss' value='" + style + "'>");

    li.append(li_span_icon);
    li.append(li_span_name);
    li.append(li_remove);
    li.append(li_edit_box_type);
    li.append(li_hidden_infoid);
    li.append(li_hidden_id);
    li.append(li_hidden_type);
    li.append(li_hidden_name);
    li.append(li_hidden_css);

    $("#datainfos").append(li);

    //加载显示html数据
    ajax({
        url: "/analysis/dashboard/getDataHtml",
        data: {
            dataid: id,
            dataType: type,
            chartStyle: JSON.stringify(special)
        },
        async: false,
        success: function (result) {
            if (result.returnCode == 1) {
                var html = result.html;
                $("#widget-chart-container").append(html);

                var functions = result.functions;
                if (functions) {
                    for (i in functions) {
                        var func = functions[i];
                        if (func) {
                            eval(func); //执行图表加载方法
                        }
                    }
                }
            }
        }
    });
}

/**
 * 删除门户数据
 * @param target
 * @param datatype
 * @param dataid
 * @param dataname
 * @param id
 */
function removeData(target, datatype, dataid, dataname, id) {
    var msg = "";
    switch (datatype) {
        case 1:
            msg = "确定要从数据门户中移除【" + dataname + "】数据图表数据吗？";
            break;
        case 2:
            msg = "确定要从数据门户中移除【" + dataname + "】电子表格数据吗？";
            break;
        case 3:
            msg = "确定要从数据门户中移除【" + dataname + "】高级表格数据吗？";
            break;
        case 4:
            msg = "确定要从数据门户中移除【" + dataname + "】高级图表数据吗？";
            break;
    }

    showInfoAlertSelect(msg, function () {
        if (id && id > 0) {
            //删除数据库中记录后移除界面dom
            var dashid = $("#dashboardid").val();
            ajax({
                url: "/analysis/dashboard/removeDashInfo",
                data: {infoid: id, id: dashid},
                success: function (result) {
                    if (result.returnCode == 1) {
                        removeDataPrivate(target, datatype, dataid);
                    }
                }
            });
        } else {
            removeDataPrivate(target, datatype, dataid);
        }
    })
}

function removeDataPrivate(target, datatype, dataid) {
    $(target).closest("li[name=datainfo]").remove();            //移除li列表
    $("#data_modal_div_" + datatype + "_" + dataid).remove();   //移除展示区域中的内容
}

/**
 *保存数据门户
 */
function saveDashboard() {
    var name = $("#dashboardname").val();
    if (name == "") {
        return showInfoAlert("数据门户名称不能为空！");
    }

    showmodalmethod(null);

    ajax({
        url: "/analysis/dashboard/saveEdit",
        data: $("#saveform").serialize(),
        success: function (result) {
            if (result.returnCode == 1) {
                var dashboardid = result.dashboardid;
                $("#dashboardid").val(dashboardid);
                var insertInfos = result.insertInfos;
                if (insertInfos) {//保存的字表信息ID也设置到对应的值上
                    for (i in insertInfos) {
                        var info = insertInfos[i];
                        $("#infoid_" + info.dataType + "_" + info.dataId).val(info.id);
                    }
                }
                showInfoAlert("数据门户保存成功！");
            } else {
                showInfoAlert("数据门户保存失败！");
            }
            canclemodalmethod();    //取消遮罩层
        }
    });
}

/**
 * 预览
 * @returns {*}
 */
function preview() {
    var dashboardid = $("#dashboardid").val();
    if (!dashboardid) {
        return showInfoAlert("请先保存数据门户再进行预览！");
    }

    window.open("/analysis/dashboard/preview?dashboardid=" + dashboardid);
}

/**
 * 盒子样式修改
 */
var _box_type_edit_li;  //当前要修改样式的字段
function editBoxType() {
    var style = $("#boxcss").val();
    _box_type_edit_li.find("input[name=specialcss]").val(style);

    $("#editBoxType").modal("hide");
}